<template>
  <div class="virtual-avatar-view">
    <h2 class="avatar-page-title">我的形象</h2>
    <div class="my-avatar-section">
      <div :style="{ backgroundImage: `url(${avatar})` }" class="my-avatar-img"></div>
    </div>
    <van-cell-group>
      <van-field v-model="avatarData.gender" label="性别" placeholder="请选择性别">
        <template #input>
          <van-radio-group v-model="avatarData.gender" direction="horizontal">
            <van-radio name="male" value="male">男</van-radio>
            <van-radio name="female" value="female">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <van-field v-model="avatarData.age" label="年龄" type="number" placeholder="请输入年龄"/>
      
      <!-- 可折叠的更改形象区域 -->
      <div class="collapse-section">
        <div class="collapse-header" @click="toggleCollapse">
          <div class="avatar-upload-title">更改形象</div>
          <van-icon :name="isCollapsed ? 'arrow-down' : 'arrow-up'" class="collapse-arrow" />
        </div>
        <div v-show="!isCollapsed" class="collapse-content">
          <div class="avatar-upload-section">
            <div class="avatar-upload-title">上传个人照片</div>
            <van-uploader v-model="avatarData.photo" />
          </div>
          <van-field v-model="avatarData.description" label="文字描述" type="textarea" placeholder="请输入文字描述" class="description-field"/>
        </div>
      </div>

      <div class="btn-wrapper" v-show="!isCollapsed">
        <van-button @click="handleGenerate" class="generate-btn">
          {{ hasGenerated ? '重新生成' : '生成形象' }}
        </van-button>
      </div>

      <!-- <van-field label="随机生成" type="number" placeholder="请输入年龄" readonly/> -->

      <div class="generated-avatars" v-show="!isCollapsed">
        <div v-for="(avatar, index) in generatedAvatars" :key="index" class="avatar-result" @click="selectAvatar(index)">
          <img :src="avatar" alt="生成的形象" :class="{ 'avatar-selected': selectedAvatar === index }" />
        </div>
      </div>
      <div v-if="selectedAvatar !== null" class="confirm-btn-wrapper" v-show="!isCollapsed">
        <van-button @click="confirmAvatar" class="confirm-btn">确认选择</van-button>
      </div>
    </van-cell-group>

    
  </div>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import type { UploaderFileListItem } from 'vant'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { storeToRefs } from 'pinia'

const router = useRouter()
const userStore = useUserStore()
const { avatar, gender, age } = storeToRefs(userStore)

/** 折叠与生成相关状态（纯前端） */
const isCollapsed = ref(true)
const hasGenerated = ref(false)
const generatedAvatars = ref<string[]>([])
const selectedAvatar = ref<number | null>(null)

/** 表单本地状态（初始取 store 值） */
const avatarData = ref({
  gender: gender.value,   // 只展示，不改 store
  age: age.value,
  description: '',
  photo: [] as UploaderFileListItem[]
})

/** 生成占位图（示例） */
function generateRandomAvatars(count: number) {
  const list: string[] = []
  for (let i = 0; i < count; i++) {
    if(i===0){
      list.push('https://ku-sheet-server.baidu-int.com/uploader/f/RbQmOajtwQw8o2qZ.png?accessToken=eyJhbGciOiJIUzI1NiIsImtpZCI6ImRlZmF1bHQiLCJ0eXAiOiJKV1QifQ.eyJleHAiOjE3NTY2MzgwOTgsImZpbGVHVUlEIjoiNlo0SXVSMTB1ZGlra0JOdSIsImlhdCI6MTc1NjYzNzQ5OCwiaXNzIjoidXBsb2FkZXJfYWNjZXNzX3Jlc291cmNlIiwidXNlcklkIjoxMDAwMDEyOTY5M30.R4qUoZ07NOt6kKD8Yc1sHLB9EE9cP3z28RTsbm-28Bs');
    }else if(i===1){
      list.push('https://ku-sheet-server.baidu-int.com/uploader/f/0nqEU0fbvrNtINRl.jpg?accessToken=eyJhbGciOiJIUzI1NiIsImtpZCI6ImRlZmF1bHQiLCJ0eXAiOiJKV1QifQ.eyJleHAiOjE3NTY2MzgwOTgsImZpbGVHVUlEIjoiNlo0SXVSMTB1ZGlra0JOdSIsImlhdCI6MTc1NjYzNzQ5OCwiaXNzIjoidXBsb2FkZXJfYWNjZXNzX3Jlc291cmNlIiwidXNlcklkIjoxMDAwMDEyOTY5M30.R4qUoZ07NOt6kKD8Yc1sHLB9EE9cP3z28RTsbm-28Bs');
    }else {
      list.push(`https://via.placeholder.com/150?text=Avatar+${Math.random().toString(36).slice(2,7)}`)
    }
    
  }
  return list
}
const handleGenerate = () => {
  const newOnes = generateRandomAvatars(2)
  generatedAvatars.value = [...newOnes, ...generatedAvatars.value].slice(0, 6)
  hasGenerated.value = true
}

const selectAvatar = (index: number) => {
  selectedAvatar.value = index
}

const confirmAvatar = () => {
  if (selectedAvatar.value === null) return
  const chosen = generatedAvatars.value[selectedAvatar.value]
  // 只调用 store；模板里 avatar 是响应式的，会自动更新
  userStore.updateAvatar(chosen)

  // 收起 & 清空候选
  isCollapsed.value = true
  generatedAvatars.value = []
  selectedAvatar.value = null
}

/** 折叠切换 */
const toggleCollapse = () => {
  isCollapsed.value = !isCollapsed.value
}

/** 可选：从本地上传里即时设置为头像（需要的话打开注释）
watch(() => avatarData.value.photo, (list) => {
  const first = list?.[0]
  if (first?.url) {
    userStore.updateAvatar(first.url)
  }
})
*/
</script>


<style scoped>
.virtual-avatar-view {
  background: #fff;
  border-radius: 8px;
  max-width: 800px;
  margin: auto;
}

.avatar-page-title {
  text-align: center;
  font-size: 28px;
  font-weight: bold;
  color: #8C5C2A;
  margin-bottom: 16px;
}

.generated-avatars {
  margin-top: 24px;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  justify-items: center;
  gap: 10px;
}

.avatar-result {
  text-align: center;
  width: 130px;
  height: 130px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.avatar-result img {
  width: 150px;
  height: 150px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.my-avatar-section {
  display: flex;
  margin: 10px 0;
  justify-content: center;
}

.my-avatar-img {
  width: 180px;
  height: 180px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.12);
  object-fit: cover;
  background: #f8f8f8;
  background-repeat: no-repeat;
  background-size: cover;
}

.avatar-upload-section {
  margin: 16px 0 8px 16px;
}

.avatar-upload-title {
  font-size: 15px;
  color: var(--van-field-label-color);
  margin-bottom: 8px;
}

.btn-wrapper {
  margin:10px 16px 0 16px;
  padding-bottom: 16px;
  display: flex;
  gap:8px;
  justify-content: flex-end;
}

.generate-btn {
  border-radius: 8px;
}

.avatar-selected {
  border: 4px solid #FFD59E;
  box-shadow: 0 0 0 6px #FFF3E0;
}

.confirm-btn-wrapper {
  display: flex;
  justify-content: flex-end;
  margin: 16px 16px 0 16px;
  padding-bottom: 16px;
}

.confirm-btn {
  border-radius: 8px;
}

/* 折叠区域样式 */
.collapse-section {
  border-top: 1px solid #ebedf0;
  margin-top: -1px;
}

.collapse-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 16px;
  cursor: pointer;
}

.collapse-arrow {
  transition: transform 0.3s;
  color: #969799;
  font-size: 16px;
}

.collapse-content {
  border-radius: 0 0 8px 8px;
}

.description-field :deep(.van-field__control) {
  min-height: 60px !important;  /* 设置最小高度 */
  max-height: 100px !important;  /* 可选：设置最大高度 */
}
</style>